package com.atdfrz.secondshop.controller.admin;

import com.atdfrz.secondshop.controller.user.BaseController;
import com.atdfrz.secondshop.dto.LayuiResult;
import com.atdfrz.secondshop.mapper.UserMapper;
import com.atdfrz.secondshop.pojo.User;
import com.atdfrz.secondshop.service.UserService;
import com.atdfrz.secondshop.service.ex.PasswordNotMatchException;
import com.atdfrz.secondshop.service.ex.UserNotFoundException;
import com.atdfrz.secondshop.service.impl.UserServiceImpl;
import com.atdfrz.secondshop.utils.JsonResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/admin")
public class AdminController extends BaseController {
    @Autowired
    private UserService userService;

    @Autowired
    private UserMapper userMapper;

    @RequestMapping("/index")//跳转到用户首页
    public String toindex(){
        return "/admin/index";
    }

    @RequestMapping("/")//跳转到登录界面
    public String tologin(){
        return "/admin/login/login";
    }

    @RequestMapping("/console")//跳转到控制台界面
    public String toconsole(){
        return "/admin/echars/console";
    }

    @RequestMapping("/sold")//跳转到销量列表界面
    public String tosold(){
        return "/admin/sold/soldrecord";
    }


    @GetMapping("/userlist")//查询普通用户列表
    public String userlist(){
        return "/admin/user/userlist";
    }



    /**
     * 管理员列表
     * */
    @GetMapping("/adminlist")//查询管理员列表
    public String adminlist(){
        return "/admin/user/adminlist";
    }

    @RequestMapping("/login")
    @ResponseBody//登录
    public LayuiResult login(@RequestBody User user, HttpSession session,Model model){
        LayuiResult<User> layuiResult = new LayuiResult<>();
        try {
            User user2 = userService.login(user.getUsername(), user.getPassword());
            layuiResult.setCode(1);
            layuiResult.setMessage("登录成功");
            session.setAttribute("user",user2);
            return layuiResult;

        }catch (UserNotFoundException e){
            layuiResult.setCode(3);
            layuiResult.setMessage("账号不存在");
            return layuiResult;
        }catch (PasswordNotMatchException e){
            layuiResult.setCode(2);
            layuiResult.setMessage("密码错误");
            return layuiResult;
        }

    }


    @RequestMapping("/logout")//退出
    public String logout(HttpSession session){
        session.invalidate();
        return "redirect:/admin/";
    }

    @RequestMapping("/getuserlist/{role}")
    @ResponseBody//查询普通用户及管理员列表信息
    public Map<String, Object> getuserlist(Integer page, Integer limit,@PathVariable("role") Integer role){
        PageHelper.startPage(page, limit);
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(role!=null,User::getRole,role);
        PageInfo<User> pageInfo = new PageInfo<>(userMapper.selectList(wrapper));
        Map<String, Object> map = new HashMap<>();
        map.put("code", "0");
        map.put("data", pageInfo.getList());
        //count是total
        map.put("count", pageInfo.getTotal());
        return map;
    }

    /**
     * 将用户封号或解封（status）
     * 0：正常  1：封号
     */
    @PutMapping("/user/forbid/{userId}/{status}")
    @ResponseBody
    public LayuiResult userStatus(@PathVariable("userId") Integer userId,@PathVariable("status") Integer status){
        LayuiResult<User> layuiResult = new LayuiResult<>();
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<User>();
        wrapper.eq(userId!=null,User::getUserId,userId);
        if (status==1) {
            //封号处理
            User user = userMapper.selectOne(wrapper);
            user.setStatus(1);
//            userMapper.insert(user);
            userMapper.update(user,wrapper);
            layuiResult.setCode(1);
            layuiResult.setMessage("封号成功");
            return layuiResult;
        }else if (status==0){//解封处理
            User user = userMapper.selectOne(wrapper);
            user.setStatus(0);
            userMapper.update(user,wrapper);
            layuiResult.setCode(2);
            layuiResult.setMessage("解封成功");
        }
        return layuiResult;
    }

    /**
     * 模糊查询
     */
    @RequestMapping("/searchByName")
    @ResponseBody
    public Map<String, Object> getUserList(String username, Integer page, Integer limit){
        PageHelper.startPage(page, limit);
        PageInfo<User> pageInfo=null;
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<User>();
        if (username==null){
            //如果没有输入名字，则查询所有
            pageInfo=new PageInfo<>(userMapper.selectList(null));
        }
        else {
            //否则则进行模糊查询
            wrapper.like(StringUtils.isNotBlank(username),User::getUsername,username);
            pageInfo=new PageInfo<>(userMapper.selectList(wrapper));
        }
        Map<String, Object> map = new HashMap<>();
        map.put("code", "0");
        map.put("data", pageInfo.getList());
        //count是total
        map.put("count", pageInfo.getTotal());
        return map;
    }

}
